package com.fenghuo.map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Ac_Camera extends Activity implements SurfaceHolder.Callback,
        OnClickListener {

    private SurfaceView surfaceView;
    private SurfaceHolder holder;
    private Camera mcamera;
    private File filepath = null;
    private static String imgPath = "/Android/photos";

    private Button btn_take;
    private Button btn_cancel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_camara);

        surfaceView = (SurfaceView) findViewById(R.id.mSurfaceView1);
        btn_take = (Button) findViewById(R.id.btn_takephoto);
        btn_cancel = (Button) findViewById(R.id.btn_quit);
        btn_cancel.setOnClickListener(this);
        btn_take.setOnClickListener(this);
        holder = surfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        checkSoftStage();
    }

    /**
     * 检测手机是否存在SD卡,网络连接是否打开
     */
    private void checkSoftStage() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) { // 判断是否存在SD卡
            String rootPath = Environment.getExternalStorageDirectory().getPath(); // 获取SD卡的根目录
            filepath = new File(rootPath + imgPath);
            if (!filepath.exists()) {
                filepath.mkdirs();
            }
        } else {
            new AlertDialog.Builder(this)
                    .setMessage("检测到手机没有存储卡！请插入手机存储卡再开启本应用。")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    finish();
                                }
                            }).show();
        }
    }

    /**
     * 自动对焦后拍照
     *
     * @author aokunsang
     * @Date 2011-12-5
     */
    private final class AutoFoucus implements AutoFocusCallback {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            if (success && mcamera != null) {
                mcamera.takePicture(mShutterCallback, null, mPictureCallback);
            }
        }
    }

    /**
     * 在相机快门关闭时候的回调接口，通过这个接口来通知用户快门关闭的事件，
     * 普通相机在快门关闭的时候都会发出响声，根据需要可以在该回调接口中定义各种动作， 例如：使设备震动
     */
    private final ShutterCallback mShutterCallback = new ShutterCallback() {
        public void onShutter() {
            Log.d("ShutterCallback", "...onShutter...");
        }
    };

    /**
     * 重点对象、 此处实例化了一个本界面的PictureCallback 当用户拍完一张照片的时候触发，这时候对图片处理并保存操作。
     */
    private final PictureCallback mPictureCallback = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                String fileName = System.currentTimeMillis() + ".jpg";
                File file = new File(filepath.getAbsolutePath(), fileName);
                Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(file, false));
                bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                bos.flush();
                bos.close();

//				Intent intent = new Intent(Ac_Camera.this, Ac_Note.class);
//				intent.putExtra("imagePath", file.getPath());
//				startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    /**
     * 打开相机,设置预览
     */
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mcamera = Camera.open(); // 打开摄像头
            mcamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            mcamera.release();
            mcamera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        Camera.Parameters param = mcamera.getParameters();
        /**
         * 设置拍照图片格式
         */
        param.setPictureFormat(PixelFormat.JPEG);
        /**
         * 设置预览尺寸【这里需要注意：预览尺寸有些数字正确，有些会报错，不清楚为啥】
         */
        // param.setPreviewSize(320, 240);
        /**
         * 设置图片大小
         */
        //param.setPictureSize(640, 480);
        param.setRotation(90);
        mcamera.setParameters(param);
        mcamera.setDisplayOrientation(90);
        /**
         * 开始预览
         */
        mcamera.startPreview();

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mcamera.stopPreview();
        if (mcamera != null) mcamera.release();
        mcamera = null;
    }

    @Override
    public void onClick(View v) {
        //  mCamera.autoFocus(new AutoFoucus());  //自动对焦
        switch (v.getId()) {
            case R.id.btn_takephoto:
                mcamera.autoFocus(new AutoFoucus());  //自动对焦
                break;
            case R.id.btn_quit:

                break;
            default:
                break;
        }
    }

}
